﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using System.ServiceModel.Description;

namespace OptionSetBatchManager
{
    public partial class LoginForm : Form
    {
        public string ServerURL { get; set; }
        public IOrganizationService Service { get; set; }

        public LoginForm()
        {
            InitializeComponent();
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            try
            {
                var serverUrl = txtServerURL.Text;
                IServiceConfiguration<IOrganizationService> orgConfigInfo =
                    ServiceConfigurationFactory.CreateConfiguration<IOrganizationService>(new Uri(string.Format("{0}/XRMServices/2011/Organization.svc", serverUrl.EndsWith("/") ? serverUrl.Substring(0, serverUrl.Length - 1) : serverUrl)));
                var credentials = new ClientCredentials();
                if (chkUserCurrentWC.Checked)
                {
                    credentials.Windows.ClientCredential = System.Net.CredentialCache.DefaultNetworkCredentials;
                }
                else
                {
                    credentials.Windows.ClientCredential = new System.Net.NetworkCredential(txtUserName.Text, txtPassword.Text, txtDomain.Text);
                }
                //credentials.Windows.ClientCredential = new System.Net.NetworkCredential(txtUserName.Text, txtPassword.Text, txtDomain.Text);
                              
                var serviceProxy = new OrganizationServiceProxy(orgConfigInfo, credentials);
                OrganizationRequest request = new OrganizationRequest("WhoAmI");
                var response = serviceProxy.Execute(request);
               
                Service = (IOrganizationService)serviceProxy;
                ServerURL = serverUrl;
                DialogResult = System.Windows.Forms.DialogResult.OK;
            }
            catch (Exception)
            {
                MessageBox.Show("Unable to connect to the server!", "Login Failed", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
        }

        private void chkUserCurrentWC_CheckedChanged(object sender, EventArgs e)
        {
            txtDomain.Enabled = !chkUserCurrentWC.Checked;
            txtUserName.Enabled = !chkUserCurrentWC.Checked;
            txtPassword.Enabled = !chkUserCurrentWC.Checked;
        }
    }
}
